<?php

header('Content-type: text/javascript');

# -- Main

$url = $_GET['url'];
if (empty($url)) { echo ''; exit; }

$location = resolveEndpointOf($url);

$callback = $_GET['callback'];
if (empty($callback)) {
  echo $location;
} else {
  echo $callback . "('" . $location . "', '" . $url . "');";
}


# -- Functions

function resolveEndpointOf($url) {
  $c = curl_init();

  curl_setopt($c, CURLOPT_URL, $url);
  curl_setopt($c, CURLOPT_FOLLOWLOCATION, false);
  curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($c, CURLOPT_HEADER, true);

  $buffer = curl_exec($c);
  $curl_info = curl_getinfo($c);
  curl_close($c);
  
  $header_size = $curl_info['header_size'];
  $header = substr($buffer, 0, $header_size);

  preg_match('/Location: (.*)/', $header, $matches);
  
  # Return the URL back again if there wasn't a Location
  if ( empty($matches[1]) ) {
    return $url;
  } else {
    return resolveEndpointOf(trim($matches[1]));
  }
}
